package com.own.component.common.mvc.intercept;

import com.own.constant.ConstantCommon;
import lombok.NonNull;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * TraceIdInterceptor
 *
 * @author chenxueli
 * @date 2022-08-30 14:04:00
 */
public class TraceIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull Object handler
    ) {
        MDC.put(ConstantCommon.TRACE_ID, UUID.randomUUID().toString());
        return true;
    }

    @Override
    public void postHandle(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull Object handler,
            ModelAndView modelAndView
    ) {
    }

    @Override
    public void afterCompletion(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull Object handler,
            Exception ex
    ) {
        // 调用结束后删除
        MDC.remove(ConstantCommon.TRACE_ID);
    }

}
